package transaction

import (
	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric-protos-go/common"
	pb "github.com/hyperledger/fabric-protos-go/peer"
)

func getChaincode(envelope *common.Envelope) (*_chaincode_info, error) {
	payload := &common.Payload{}
	err := proto.Unmarshal(envelope.Payload, payload)
	if err != nil {
		return nil, err
	}

	// -------------------- channel header ---------------
	channelHeader := &common.ChannelHeader{}
	err = proto.Unmarshal(payload.Header.ChannelHeader, channelHeader)
	if err != nil {
		return nil, err
	}
	// channel Header extension 解析
	chaincodeHeaderExtension := &pb.ChaincodeHeaderExtension{}
	err = proto.Unmarshal(channelHeader.Extension, chaincodeHeaderExtension)
	if err != nil {
		return nil, err
	}
	//fmt.Printf("---> ChannelHeader extension\n%#v\n", chaincodeHeaderExtension)
	//fmt.Printf("---> ChannelHeader extension, chaincodeID\n%#v\n", chaincodeHeaderExtension.ChaincodeId)
	//fmt.Printf("---> ChannelHeader extension, chaincodeID\n%#v\n", chaincodeHeaderExtension.ChaincodeId.Name)

	cc := _chaincode_info{}
	cc.ChaincodeName = chaincodeHeaderExtension.ChaincodeId.Name
	cc.ChaincodeVer = chaincodeHeaderExtension.ChaincodeId.Version

	return &cc, nil
}
